package com.company.management.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.company.management.config.CustomConfig;
import com.company.management.domain.reward.ScoreLevel;
import com.company.management.domain.reward.ScoreLog;
import com.company.management.dto.*;
import com.company.management.mapper.*;
import com.company.management.mapper.reward.ScoreLevelMapper;
import com.company.management.mapper.reward.ScoreLogMapper;
import com.company.management.modal.entity.*;
import com.company.management.result.Code;
import com.company.management.result.Result;
import com.company.management.service.report.TaskService;
import com.company.management.utils.SnowflakeIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private DepartMentMapper departmentMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private StepMapper stepMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FileDataMapper fileDataMapper;
    @Resource
    private CustomConfig config;
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    @Autowired
    private ScoreLevelMapper scoreLevelMapper;
    @Autowired
    private ScoreLogMapper scoreLogMapper;

    private SnowflakeIdGeneratorUtil idGeneratorUtil = new SnowflakeIdGeneratorUtil(1, 1);

    /**
     * 批量创建任务
     *
     * @param req
     * @return
     */
    @Override
    public Result createTask(CreateTaskReq req) {
        List<CreateTaskInfo> list = req.getList();
        for (CreateTaskInfo info : list) {
            Task task = new Task();
            String taskid = UUID.randomUUID().toString();
            task.setTaskId(taskid);
            task.setTaskContent(info.getTaskContent());
            task.setCreateDateTime(LocalDateTime.now());
            task.setFlag(0);
            task.setFinishStatus(0);
            task.setValidFlag(1);
            task.setCreateID(req.getUserId());
            task.setVersionNum(0);//版本号
            task.setRepeatFlag(info.getRepeatFlag());
            if ("6".equals(info.getRepeatFlag())) {
                task.setRepeatCircle(info.getRepeatCircle());
                task.setRepeatUnit(info.getRepeatUnit());
                task.setRepeatExtFields(info.getRepeatExtFields());
            }
            task.setDeadTime(LocalDateTime.parse(info.getNoticeDateTime(), formatter));
            task.setBackUpId(idGeneratorUtil.nextId());
            taskMapper.insert(task);
            List<CreateStepInfo> steps = info.getSteps();
            if (CollectionUtils.isNotEmpty(steps)) {
                for (CreateStepInfo createStepInfo : steps) {
                    //新增
                    Step step = new Step();
                    step.setTaskId(taskid);
                    step.setStepId(UUID.randomUUID().toString());
                    step.setValidFlag(1);
                    step.setCreateID(req.getUserId());
                    step.setCreateDateTime(LocalDateTime.now());
                    step.setStepContent(createStepInfo.getStepContent());
                    stepMapper.insert(step);
                }
            }
        }
        return new Result(Code.statusCode_200, "任务创建成功");
    }


    /**
     * 批量修改任务
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateTask(UpdateTaskReq req) {
        for (UpdateTaskInfo info : req.getList()) {
            if (null == info.getTaskId()) {
                Task task = new Task();
                String taskid = UUID.randomUUID().toString();
                task.setTaskId(taskid);
                task.setTaskContent(info.getTaskContent());
                task.setCreateDateTime(LocalDateTime.parse(info.getCreateDateTime(), formatter));
                task.setFlag(0);
                task.setFinishStatus(0);
                task.setValidFlag(1);
                task.setCreateID(req.getUserId());
                task.setVersionNum(0);//版本号
                task.setRepeatFlag(info.getRepeatFlag());
                task.setDeadTime(null == info.getDeadTime() ? null : LocalDateTime.parse(info.getDeadTime(), formatter));
                task.setNoticeDateTime(null == info.getNoticeDateTime() ? null : LocalDateTime.parse(info.getNoticeDateTime(), formatter));
                task.setNote(info.getNote());
                task.setRepeatCircle(info.getRepeatCircle());
                task.setRepeatUnit(info.getRepeatUnit());
                task.setRepeatExtFields(info.getRepeatExtFields());
                task.setRepeatFlag(info.getRepeatFlag());//重复标识
                task.setBackUpId(idGeneratorUtil.nextId());
                taskMapper.insert(task);
                List<CreateStepInfo> steps = info.getSteps();
                if (CollectionUtils.isNotEmpty(steps)) {
                    for (CreateStepInfo createStepInfo : steps) {
                        //新增
                        Step step = new Step();
                        step.setTaskId(taskid);
                        step.setStepId(UUID.randomUUID().toString());
                        step.setValidFlag(1);
                        step.setCreateID(req.getUserId());
                        step.setCreateDateTime(LocalDateTime.now());
                        step.setStepContent(createStepInfo.getStepContent());
                        stepMapper.insert(step);
                    }
                }
            } else if (null != info.getDeleted() && 1 == info.getDeleted()) {
//                QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
//                Task task = new Task();
//                task.setTaskId(info.getTaskId());
//                task.setValidFlag(0);
//                queryWrapper.setEntity(task);
                taskMapper.updateData(info.getTaskId());
                Step step = new Step();
                step.setTaskId(info.getTaskId());
                step.setValidFlag(0);
                stepMapper.updateById(step);
            } else {
                Task task = new Task();
                task.setTaskId(info.getTaskId());
                task.setTaskContent(info.getTaskContent());
                task.setFinishStatus(info.getFinishStatus());
                task.setFlag(info.getFlag());
                task.setNoticeDateTime(null == info.getNoticeDateTime() ? null : LocalDateTime.parse(info.getNoticeDateTime(), formatter));
                task.setEndDateTime(null == info.getEndDateTime() ? null : LocalDateTime.parse(info.getEndDateTime(), formatter));
                task.setNote(info.getNote());
                task.setRepeatFlag(info.getRepeatFlag());//重复标识
                Task taskvo = taskMapper.selectById(info.getTaskId());
                if (Objects.nonNull(taskvo) && null != taskvo.getVersionNum()) {
                    task.setVersionNum(taskvo.getVersionNum() + 1);
                }

                task.setDeadTime(null == info.getDeadTime() ? null : LocalDateTime.parse(info.getDeadTime(), formatter));
                task.setRepeatCircle(info.getRepeatCircle());
                task.setRepeatUnit(info.getRepeatUnit());
                task.setRepeatExtFields(info.getRepeatExtFields());
                taskMapper.updateById(task);
                List<CreateStepInfo> steps = info.getSteps();
                if (CollectionUtils.isNotEmpty(steps)) {
                    for (CreateStepInfo createStepInfo : steps) {
                        String stepId = createStepInfo.getStepId();
                        Step step = new Step();
                        step.setStepContent(createStepInfo.getStepContent());
                        if (null != stepId) {
                            step.setStepId(stepId);
                            //删除标识
                            if (null != createStepInfo.getDeleted() && 1 == createStepInfo.getDeleted()) {
                                step.setValidFlag(0);//删除的
                            } else {
                                //更新
                                step.setFinishStatus(createStepInfo.getFinishStatus());
                            }
                            stepMapper.updateById(step);
                        } else {
                            //新增
                            step.setTaskId(info.getTaskId());
                            step.setValidFlag(1);//生效
                            step.setFinishStatus(0);
                            step.setStepId(UUID.randomUUID().toString());
                            step.setCreateDateTime(LocalDateTime.now());
                            stepMapper.insert(step);
                        }
                    }
                }
                List<FileInfoDeleted> fileList = info.getFileList();
                for (FileInfoDeleted fileInfo : fileList) {
                    if (null != fileInfo.getDeleted() && 1 == fileInfo.getDeleted()) {
                        FileData Info = new FileData();
                        Info.setFileId(fileInfo.getFileId());
                        Info.setTaskId(info.getTaskId());
                        Info.setValidFlag(0);
                        fileDataMapper.updateById(Info);
                    }
                }


            }


        }
        return new Result(Code.statusCode_200, "任务修改成功");
    }

    /**
     * 查询任务
     *
     * @return
     */
    @Override
    public Result selectTaskList(User user) {
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        Task task = new Task();
        task.setValidFlag(1);
        task.setCreateID(user.getUserId());
        queryWrapper.setEntity(task);
        List<Task> tasks = taskMapper.selectList(queryWrapper);
        List<QueryTaskVo> list = new ArrayList<>();

        for (Task dto : tasks) {
            QueryTaskVo queryTaskVo = new QueryTaskVo();
            TaskProcessDto taskProcessDto = new TaskProcessDto();
            queryTaskVo.setTaskContent(dto.getTaskContent());
            queryTaskVo.setFlag(dto.getFlag());
            queryTaskVo.setTaskId(dto.getTaskId());
            queryTaskVo.setFinishStatus(dto.getFinishStatus());
            queryTaskVo.setCreateID(dto.getCreateID());
            queryTaskVo.setNote(dto.getNote());
            queryTaskVo.setConfirmUserId(dto.getConfirmUserId());
            queryTaskVo.setConfirmDateTime(null == dto.getConfirmDateTime() ? null : dto.getConfirmDateTime().format(formatter));
            queryTaskVo.setFileData(dto.getFileData());
            queryTaskVo.setEndDateTime(null == dto.getEndDateTime() ? null : dto.getEndDateTime().format(formatter));
            queryTaskVo.setNoticeDateTime(null == dto.getNoticeDateTime() ? null : dto.getNoticeDateTime().format(formatter));
            queryTaskVo.setAssignId(dto.getAssignId());
            queryTaskVo.setFromId(dto.getFromId());
            if(null!= dto.getFromId()){
                User user0 = userMapper.selectById(dto.getFromId());
                if(Objects.nonNull(user0)){
                    queryTaskVo.setFromName(user0.getUserName());
                }
            }
            queryTaskVo.setShareDateTime(null == dto.getShareDateTime() ? null : dto.getShareDateTime().format(formatter));
            queryTaskVo.setCreateDateTime(null == dto.getCreateDateTime() ? null : dto.getCreateDateTime().format(formatter));
            queryTaskVo.setVersionNum(dto.getVersionNum());
            queryTaskVo.setRepeatFlag(dto.getRepeatFlag());
            queryTaskVo.setRepeatCircle(dto.getRepeatCircle());
            queryTaskVo.setRepeatUnit(dto.getRepeatUnit());
            queryTaskVo.setRepeatExtFields(dto.getRepeatExtFields());
            queryTaskVo.setDeadTime(null == dto.getDeadTime() ? null : dto.getDeadTime().format(formatter));
            List<QueryStepVo> listStep = new ArrayList<>();
            List<FileInfo> listFile = new ArrayList<>();

            if (null != dto.getTaskId()) {

                QueryWrapper<Step> queryStepWrapper = new QueryWrapper<>();
                Step step = new Step();
                step.setTaskId(dto.getTaskId());
                step.setValidFlag(1);
                queryStepWrapper.orderByAsc("CreateDateTime");
                queryStepWrapper.setEntity(step);
                List<Step> listinfo = stepMapper.selectList(queryStepWrapper);

                for (Step p : listinfo) {
                    QueryStepVo stepVo = new QueryStepVo();
                    stepVo.setStepContent(p.getStepContent());
                    stepVo.setStepId(p.getStepId());
                    stepVo.setFinishStatus(p.getFinishStatus());
                    listStep.add(stepVo);
                }


                QueryWrapper<FileData> queryFileWrapper = new QueryWrapper<>();
                FileData fileData = new FileData();
                if (null != dto.getTaskParentId()) {
                    fileData.setTaskId(dto.getTaskParentId());
                } else {
                    fileData.setTaskId(dto.getTaskId());
                }
                fileData.setValidFlag(1);
                queryFileWrapper.orderByAsc("CreateDateTime");
                queryFileWrapper.setEntity(fileData);
                List<FileData> listFileInfo = fileDataMapper.selectList(queryFileWrapper);

                for (FileData f : listFileInfo) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setFileId(f.getFileId());
                    fileInfo.setFileName(f.getFileMc());
                    fileInfo.setFileType(f.getFileType());
                    fileInfo.setFileUrl(f.getFileUrl());
                    fileInfo.setFileSize(f.getFileSize());
                    listFile.add(fileInfo);
                }
            }
            String strIds = dto.getAssignId();
            String taskId = dto.getTaskId();
            List<TaskProcessDto> listAssignList = new ArrayList<>();
            if (null != strIds) {
                String[] assignList = strIds.split(",");
                for (String createId : assignList) {
                    TaskProcessDto taskProcessDto01 = new TaskProcessDto();
                    QueryWrapper<Task> queryTaskContion = new QueryWrapper<>();
                    Task con = new Task();
                    con.setTaskParentId(taskId);
                    con.setCreateID(Integer.parseInt(createId));
                    queryTaskContion.setEntity(con);
                    Task taskinfo = taskMapper.selectOne(queryTaskContion);
                    String childTaskId = taskinfo.getTaskId();
                    QueryWrapper<Step> queryStep = new QueryWrapper<>();
                    Step step = new Step();
                    step.setTaskId(childTaskId);
                    step.setValidFlag(1);
                    queryStep.setEntity(step);
                    List<Step> allList = stepMapper.selectList(queryStep);
                    int stepCount = allList.size();
                    taskProcessDto01.setStepCount(stepCount);
                    int finshCount=0;
                    if(0!=stepCount){
                        System.out.println("========stepCount=========="+stepCount);
                        finshCount = (int) (allList.stream().filter(stepItem -> null != stepItem.getFinishStatus() && stepItem.getFinishStatus() == 1).count());
                    }
                    taskProcessDto01.setFinishCount(finshCount);
                    taskProcessDto01.setFinishStatus(taskinfo.getFinishStatus());
                    User userInfo = userMapper.selectById(Integer.parseInt(createId));
                    taskProcessDto01.setUserName(userInfo.getUserName());
                    taskProcessDto01.setAvatar(userInfo.getAvatar());



                    listAssignList.add(taskProcessDto01);
                }
            }
            queryTaskVo.setSteps(listStep);
            queryTaskVo.setFileList(listFile);
            queryTaskVo.setProcessList(listAssignList);
            list.add(queryTaskVo);
        }
        return new Result(Code.statusCode_200, list);
    }


    /**
     * 批量删除任务
     *
     * @param req
     * @return
     */
    @Override
    public Result deleteTask(TaskDeleReq req) {
        //判断当前列表id是否为空
        if (StringUtils.isBlank(req.getTaskIds())) {
            return new Result(Code.statusCode_406, "任务Id不能为空");
        }
        //用逗号分隔
        String taskIdsStr = req.getTaskIds();
        String[] taskIdArray = taskIdsStr.split(",");
        List<String> taskIds = new ArrayList<>();
        for (String id : taskIdArray) {
            taskIds.add(id);
        }

        for (String taskId : taskIds) {
            Task task = new Task();
            task.setTaskId(taskId);
            task.setValidFlag(0);
            taskMapper.updateById(task);
            Step step = new Step();
            step.setTaskId(taskId);
            step.setValidFlag(0);
            stepMapper.updateById(step);
        }


        return new Result(Code.statusCode_200, "删除成功");
    }


    /**
     * 查看任务详情
     *
     * @param req
     * @return
     */
    @Override
    public Result queryTaskDetail(QueryTaskDetailReq req) {
        //判断当前列表id是否为空
        if (null == req.getTaskId()) {
            return new Result(Code.statusCode_406, "任务Id不能为空");
        }
        QueryWrapper<Task> queryTaskWrapper = new QueryWrapper<>();
        Task task = new Task();
        task.setTaskId(req.getTaskId());
        task.setValidFlag(1);//未被删除的任务
        queryTaskWrapper.setEntity(task);
        Task taskinfo = taskMapper.selectOne(queryTaskWrapper);
        QueryTaskVo qeryTaskVo = new QueryTaskVo();
        BeanUtils.copyProperties(taskinfo, qeryTaskVo);
        qeryTaskVo.setCreateDateTime(null == task.getCreateDateTime() ? null : task.getCreateDateTime().format(formatter));
        return new Result(Code.statusCode_200, qeryTaskVo);
    }


    /**
     * 批量创建步骤
     *
     * @param req
     * @return
     */
    @Override
    public Result createStep(CreateStepReq req) {
        List<CreateStepInfo> list = req.getList();
        for (CreateStepInfo info : list) {
            Step step = new Step();
            step.setStepId(UUID.randomUUID().toString());
            step.setStepContent(info.getStepContent());
            step.setCreateDateTime(LocalDateTime.now());
            step.setFinishStatus(0);
            step.setValidFlag(1);//有效标识：未删除
            step.setTaskId(null);
            stepMapper.insert(step);
        }
        return new Result(Code.statusCode_200, "步骤创建成功");
    }


    /**
     * 批量修改步骤
     *
     * @param req
     * @return
     */
    @Override
    public Result updateStep(UpdateStepReq req) {
        for (UpdateStepInfo info : req.getList()) {
            if (null == info.getStepId()) {
                return new Result(Code.statusCode_406, "修改步骤Id不能为空");
            }
            Step step = new Step();
            step.setStepId(info.getStepId());
            step.setStepContent(info.getStepContent());
            step.setTaskId(info.getTaskId());
            stepMapper.updateById(step);
        }
        return new Result(Code.statusCode_200, "步骤修改成功");
    }

    /**
     * 批量删除步骤
     *
     * @return
     */
    @Override
    public Result deleteStep(StepDeleReq req) {
        //判断当前列表id是否为空
        if (StringUtils.isBlank(req.getStepIds()) || null == req.getTaskId()) {
            return new Result(Code.statusCode_406, "步骤Id和任务Id不能为空");
        }
        //用逗号分隔
        String stepIdsStr = req.getStepIds();
        String[] stepIdArray = stepIdsStr.split(",");
        List<String> stepIds = new ArrayList<>();
        for (String id : stepIdArray) {
            stepIds.add(id);
        }
        for (String stepId : stepIds) {
            Step step = new Step();
            step.setTaskId(req.getTaskId());
            step.setStepId(stepId);
            step.setValidFlag(0);//删除状态为0：失效
            stepMapper.updateById(step);
        }
        return new Result(Code.statusCode_200, "删除成功");
    }


    /**
     * 查看任务详情
     *
     * @param req
     * @return
     */
    @Override
    public Result queryStepDetail(QueryStepDetailReq req) {
        //判断当前列表id是否为空
        if (null == req.getStepId()) {
            return new Result(Code.statusCode_406, "步骤Id不能为空");
        }

        String stepId = req.getStepId();
        QueryWrapper<Step> queryStepWrapper = new QueryWrapper<>();
        Step step = new Step();
        step.setStepId(stepId);
        step.setValidFlag(1);
        queryStepWrapper.setEntity(step);
        stepMapper.selectOne(queryStepWrapper);
        return new Result(Code.statusCode_200, "查询步骤详情成功");
    }


    /**
     * 附件上传
     *
     * @return
     */
    public Result uploadFile(fileInfoReq req, String uploadDir) {

        String fileName = req.getFileName();
//        String UPLOAD_DIR = "D://uploads//";
        if (StringUtils.isBlank(fileName)) {
            return new Result(Code.statusCode_406, "上传文件不能为空: " + fileName);
        }
        try {
            // 确保目录存在
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 将文件保存至指定位置
            byte[] bytes = fileName.getBytes();
            Path path = Paths.get(uploadDir + fileName);
            Files.write(path, bytes);
            return new Result(Code.statusCode_200, path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(Code.statusCode_406, "文件上传失败: " + fileName);
    }

    /**
     * 查询人员接口
     *
     * @return
     */
    @Override
    public Result getuserlist() {
        Wrapper<DepartMent> queryWrapper = new QueryWrapper<>();
        List<DepartMent> list = departmentMapper.selectList(queryWrapper);
        List<QueryUserInfoVo> queryList = new ArrayList<>();
        for (DepartMent department : list) {
            QueryUserInfoVo queryUserInfoVo = new QueryUserInfoVo();
            Integer deptId = department.getDeptId();
            String deptName = department.getDeptName();
            queryUserInfoVo.setDeptId(deptId);
            queryUserInfoVo.setDeptName(deptName);
            QueryWrapper<User> condition = new QueryWrapper<>();
            User user = new User();
            user.setDeptId(deptId);
            user.setIsAdmin(0);
            user.setEmpStatus(0);
            condition.setEntity(user);
            List<User> userList = userMapper.selectList(condition);
            List<UserInfoVo> uList = new ArrayList<>();
            for (User u : userList) {
                UserInfoVo userInfoVo = new UserInfoVo();
                userInfoVo.setUserId(String.valueOf(u.getUserId()));
                userInfoVo.setUserName(u.getUserName());
                uList.add(userInfoVo);
            }
            queryUserInfoVo.setUserList(uList);
            queryList.add(queryUserInfoVo);
        }


        return new Result(Code.statusCode_200, queryList);
    }

    /**
     * 分配任务接口
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result assigntask(AssignTaskReq req) {
        String taskId = req.getTaskId();
        String userIds = req.getUserIds();
        Task task = taskMapper.selectById(taskId);
        task.setAssignId(userIds.trim());
        taskMapper.updateById(task);
        if (Objects.isNull(task)) {
            return new Result(Code.statusCode_407, "该分配的任务不存在");
        }

        QueryWrapper<Task> querytaskInfoWrapper = new QueryWrapper<>();
        Task task0 = new Task();
        task0.setTaskParentId(taskId);
        querytaskInfoWrapper.setEntity(task0);
        List<Task> taskinfo = taskMapper.selectList(querytaskInfoWrapper);
        if (CollectionUtils.isNotEmpty(taskinfo)) {
            return new Result(Code.statusCode_407, "该任务已经被分配，请重新选择");
        }

        List<String> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(userIds)) {
            String[] users = userIds.split(",");
            for (String userid : users) {
                list.add(userid);
            }
        }

        QueryWrapper<Step> queryWrapper = new QueryWrapper<>();
        Step step001 = new Step();
        step001.setTaskId(task.getTaskId());
        step001.setValidFlag(1);
        queryWrapper.setEntity(step001);
        List<Step> listStep = stepMapper.selectList(queryWrapper);
        for (String userId : list) {
            Task assignTask = new Task();
            String taskId001 = UUID.randomUUID().toString();
            assignTask.setTaskId(taskId001);
            assignTask.setTaskContent(task.getTaskContent());
            assignTask.setFlag(0);
            assignTask.setNote(task.getNote());
            assignTask.setValidFlag(1);
            assignTask.setFinishStatus(0);
            assignTask.setCreateID(Integer.parseInt(userId));
            assignTask.setFromId(req.getUserId());
            assignTask.setVersionNum(0);
            assignTask.setCreateDateTime(LocalDateTime.now());
            assignTask.setEndDateTime(null == task.getEndDateTime() ? null : task.getEndDateTime());
            assignTask.setNoticeDateTime(task.getNoticeDateTime());
            assignTask.setDeadTime(task.getDeadTime());
            assignTask.setShareDateTime(LocalDateTime.now());
//            assignTask.setRepeatCircle(task.getRepeatCircle());
//            assignTask.setRepeatUnit(task.getRepeatUnit());
//            assignTask.setRepeatExtFields(task.getRepeatExtFields());
            assignTask.setTaskParentId(taskId);
            assignTask.setBackUpId(idGeneratorUtil.nextId());
            taskMapper.insert(assignTask);
            for (Step step : listStep) {
                Step newStep = new Step();
                BeanUtils.copyProperties(step, newStep);
                newStep.setTaskId(taskId001);
                newStep.setStepId(UUID.randomUUID().toString());
                stepMapper.insert(newStep);
            }
        }

        return new Result(Code.statusCode_200, "任务分配成功");
    }

    /**
     * 分配任务接口
     *
     * @return
     */
    @Override
    public Result uploadFile(MultipartFile file, String taskId, Integer userId, String uploadDir) {
//        for (MultipartFile  fileInfo : files) {
        String fileName = file.getOriginalFilename();
        FileData fileVo = new FileData();
        String fileId = UUID.randomUUID().toString();
        fileVo.setFileId(fileId);
        fileVo.setValidFlag(1);
        fileVo.setTaskId(taskId);
        fileVo.setCreateID(userId);
        fileVo.setCreateDateTime(LocalDateTime.now());
        String fileSuffix = "";
        try {
            // 确保目录存在
            File dir = new File(config.getAvartar_folder());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            if (fileName != null && fileName.contains(".")) {
                fileSuffix = fileName.substring(fileName.lastIndexOf("."));
                fileVo.setFileType(fileSuffix);
            }
            // 将文件保存至指定位置
            Path path = Paths.get(config.getAvartar_folder() + fileId + fileSuffix);
            file.transferTo(path);
            fileVo.setFileMc(fileName);
            String fileUrl = StrUtil.format("/api/users/showAvatar/{}", fileId + fileSuffix);
            fileVo.setFileUrl(fileUrl);
            fileVo.setFileSize(String.valueOf(Files.size(path)));
            fileDataMapper.insert(fileVo);
            Task targetTask = taskMapper.selectById(taskId);
            Integer targetVersion = targetTask.getVersionNum();
            targetTask.setVersionNum(targetVersion+1);
            taskMapper.updateById(targetTask);

            return new Result(Code.statusCode_200, path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result(Code.statusCode_200, "文件上传成功");
    }
}
